//
//  YYPNetworkTools.swift
//  weibo
//
//  Created by youyongpeng on 15/11/22.
//  Copyright © 2015年 youyongpeng. All rights reserved.
//

import UIKit
import AFNetworking


// http 请求定义枚举
enum YYPRequestMethod: String {

    case GET = "GET"
    case POST = "POST"
}


/// 网络工具
class YYPNetworkTools: AFHTTPSessionManager {
    
    // MARK: - 应用程序信息
    private let appKey = "2356220612"
    private let appSecret = "5cb99d3d758c8a9787c3745f3da7d2b9"
    private let redirectUrl = "http://www.baidu.com"


    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias YYPRequestCallBack = (result: AnyObject?, error: NSError?)->()
    

    
    //单利
    static let sharedTools: YYPNetworkTools = {
    
        let tools = YYPNetworkTools(baseURL: nil)
        
        // 设置文本格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    
    // 创建一个 token 字典
    private var tokenDict: [String: AnyObject]? {
    
        // 判断 token 是否有效
        if let token = UserAccountViewModel.sharedAccoint.accessToken {
        
            return ["access_token":token]
        }
        return nil
    }
    
}

// MARK: - 用户相关的方法

extension YYPNetworkTools {
    

    func loadUserInfo(uid: String, finished:YYPRequestCallBack) {
        
        // 获取token字典
        
        guard var parments = tokenDict else {
            
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -100, userInfo: ["message":"token不能为空"]))
            
            return
        }
        
        parments["uid"] = uid
    
        let urlString = "https://api.weibo.com/2/users/show.json"
        
//        let parments = ["uid":uid, "access_token":access_token]
        
        request(.GET, urlString: urlString, parameters: parments, finished: finished)
    }
}

// MARK: - OAuth 的相关方法
extension YYPNetworkTools {

    /// OAuth 授权 URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }

    /// 加载 AccessToken
    func loadAccessToken(code: String, finished: YYPRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(.POST, urlString: urlString, parameters: params, finished: finished)
    }

    
}

extension YYPNetworkTools {

    func request(method: YYPRequestMethod, urlString: String, parameters:[String:AnyObject]?, finished:(result: AnyObject?, error: NSError?) -> ()) {
    
        // 定义成功回调
        let success = {(task: NSURLSessionDataTask?, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        
        // 定义失败回调
        let failure = {(task: NSURLSessionDataTask?, error: NSError) -> Void in
        
            print(error)
            finished(result: nil, error: error)
        }
        
        
        // 判断
        if method == YYPRequestMethod.GET {
            GET(urlString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, success: success, failure: failure)
        }
        
    }
}